package com.study.base.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @description: NIOServer
 * @date: 2021/1/21 17:32
 * @author: hcm
 * @version: 1.0
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        //1.创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //2.得到一个select对象
        Selector selector = Selector.open();

        //3.绑定一个端口,在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(666));

        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        //把serverSocketChannel 注册到selector 关心事件为op_accept
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等待客户端连接
        while (true){
            if(selector.select(1000) == 0){
                //没有事件发生
                System.out.println("服务器等待了1秒，无连接");
                continue;
            }
            //获取相关的selectionkey集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //根据key选择通道发生的事件做相应的处理
                if(key.isAcceptable()){
                    //给该客户端生成socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功");
                    //将socketchannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到 selector
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                if(key.isReadable()){
                    //发生了读事件
                    //反向获取对饮的channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端"+new String(buffer.array()));

                }
                //手动从集合中移除当前的sselectionkey，防止重复操作
                iterator.remove();

            }
        }

    }
}
